const httpStatus = require('http-status');
const NutritionGoal = require('../models/nutritionGoal.model');
const ApiError = require('../utils/ApiError');
const logger = require('../config/logger');

/**
 * 创建用户营养目标
 * @param {Object} goalData
 * @returns {Promise<NutritionGoal>}
 */
const createNutritionGoal = async (goalData) => {
  logger.info('【营养目标创建】开始创建用户营养目标');
  logger.debug('【营养目标创建】目标内容:', JSON.stringify({
    userId: goalData.userId,
    caloriesGoal: goalData.caloriesGoal,
    macroRatio: goalData.macroRatio,
  }));

  // 检查用户是否已有营养目标
  const existingGoal = await NutritionGoal.findOne({
    userId: goalData.userId,
    isDeleted: { $ne: true }
  });

  if (existingGoal) {
    logger.warn(`【营养目标创建】用户 ${goalData.userId} 已有营养目标，请使用更新操作`);
    throw new ApiError(httpStatus.BAD_REQUEST, '用户已经设置过营养目标，请使用更新接口');
  }

  try {
    const nutritionGoal = await NutritionGoal.create(goalData);
    logger.info(`【营养目标创建】创建成功, ID: ${nutritionGoal._id}`);
    return nutritionGoal;
  } catch (error) {
    logger.error('【营养目标创建】创建失败:', error);
    throw error;
  }
};

/**
 * 获取用户营养目标
 * @param {ObjectId} userId
 * @returns {Promise<NutritionGoal>}
 */
const getNutritionGoalByUserId = async (userId) => {
  logger.info(`【营养目标查询】查询用户 ${userId} 的营养目标`);
  
  try {
    const nutritionGoal = await NutritionGoal.findOne({
      userId,
      isDeleted: { $ne: true }
    });
    
    if (nutritionGoal) {
      logger.info(`【营养目标查询】找到用户 ${userId} 的营养目标`);
    } else {
      logger.info(`【营养目标查询】用户 ${userId} 尚未设置营养目标`);
    }
    
    return nutritionGoal;
  } catch (error) {
    logger.error(`【营养目标查询】查询出错:`, error);
    throw error;
  }
};

/**
 * 更新用户营养目标
 * @param {ObjectId} userId
 * @param {Object} updateData
 * @returns {Promise<NutritionGoal>}
 */
const updateNutritionGoal = async (userId, updateData) => {
  logger.info(`【营养目标更新】更新用户 ${userId} 的营养目标`);
  logger.debug('【营养目标更新】更新内容:', JSON.stringify(updateData));
  
  try {
    const nutritionGoal = await NutritionGoal.findOne({
      userId,
      isDeleted: { $ne: true }
    });
    
    if (!nutritionGoal) {
      logger.warn(`【营养目标更新】用户 ${userId} 尚未设置营养目标`);
      throw new ApiError(httpStatus.NOT_FOUND, '未找到用户的营养目标');
    }
    
    // 更新前验证宏量营养素比例总和是否为100%
    if (updateData.macroRatio) {
      const currentRatio = { ...nutritionGoal.macroRatio.toObject(), ...updateData.macroRatio };
      const sum = currentRatio.protein + currentRatio.fat + currentRatio.carbohydrate;
      if (sum !== 0 && Math.abs(sum - 100) > 0.01) {
        logger.warn(`【营养目标更新】宏量营养素比例总和不为100%, 实际为 ${sum}%`);
        throw new ApiError(httpStatus.BAD_REQUEST, '宏量营养素比例总和必须为100%');
      }
    }
    
    Object.assign(nutritionGoal, updateData);
    await nutritionGoal.save();
    logger.info(`【营养目标更新】更新成功`);
    return nutritionGoal;
  } catch (error) {
    logger.error(`【营养目标更新】更新出错:`, error);
    throw error;
  }
};

/**
 * 删除用户营养目标（逻辑删除）
 * @param {ObjectId} userId
 * @returns {Promise<NutritionGoal>}
 */
const deleteNutritionGoal = async (userId) => {
  logger.info(`【营养目标删除】删除用户 ${userId} 的营养目标`);
  
  try {
    const nutritionGoal = await NutritionGoal.findOne({
      userId,
      isDeleted: { $ne: true }
    });
    
    if (!nutritionGoal) {
      logger.warn(`【营养目标删除】用户 ${userId} 尚未设置营养目标`);
      throw new ApiError(httpStatus.NOT_FOUND, '未找到用户的营养目标');
    }
    
    nutritionGoal.isDeleted = true;
    await nutritionGoal.save();
    logger.info(`【营养目标删除】删除成功`);
    return nutritionGoal;
  } catch (error) {
    logger.error(`【营养目标删除】删除出错:`, error);
    throw error;
  }
};

module.exports = {
  createNutritionGoal,
  getNutritionGoalByUserId,
  updateNutritionGoal,
  deleteNutritionGoal,
};